package edu.thu.studio.ormdesigner.outline;

import org.eclipse.gef.EditDomain;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.parts.ContentOutlinePage;
import org.eclipse.gef.ui.parts.TreeViewer;
import org.eclipse.jface.action.IAction;
import org.eclipse.swt.widgets.Composite;

import edu.thu.studio.ormdesigner.model.ORMModel;
import edu.thu.studio.ormdesigner.outline.action.CreateDomainAction;
import edu.thu.studio.ormdesigner.outline.action.CreateDiagramAction;
import edu.thu.studio.ormdesigner.outline.action.UpdateDomainAction;
import edu.thu.studio.ormdesigner.outline.action.UpdateDiagramAction;

public class OutlinePage extends ContentOutlinePage {
    
    private TreeViewer viewer;
    
    private ORMModel model;
    
    private ActionRegistry outlineActionRegistory;
    
    public OutlinePage(ORMModel model, EditDomain editDomain) {
        super(new TreeViewer());
        
        this.viewer = (TreeViewer) this.getViewer();
        viewer.setEditDomain(editDomain);
        this.model = model;
        
        this.outlineActionRegistory = new ActionRegistry();
        this.registerAction(this.viewer, outlineActionRegistory);
        this.viewer.setContextMenu(new OutlinePopupMenuManager(model, outlineActionRegistory, outlineActionRegistory,
            viewer));
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void createControl(Composite parent) {
        super.createControl(parent);
        
        OutlineEditPartFactory editPartFactory = new OutlineEditPartFactory();
        this.viewer.setEditPartFactory(editPartFactory);
        this.viewer.setContents(this.model);
        
        this.model.refreshOutline();
    }
    
    private void registerAction(TreeViewer treeViewer, ActionRegistry actionRegistry) {
        IAction[] actions = {new CreateDomainAction(treeViewer), new CreateDiagramAction(treeViewer),
            new UpdateDomainAction(treeViewer), new UpdateDiagramAction(treeViewer)};
        
        for (IAction action : actions) {
            actionRegistry.registerAction(action);
        }
    }
    
    public ActionRegistry getOutlineActionRegistory() {
        return outlineActionRegistory;
    }
    
    public EditPartViewer getTreeView() {
        return this.viewer;
    }
    
}
